package com.jixiantubu.adapter;

import java.util.List;

import com.example.jixiantubu.R;
import com.jixiantubu.util.MyApplication;
import com.lidroid.xutils.BitmapUtils;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class PostInfo_TupianAdapter extends BaseAdapter {

	Context context;
	List<String> list;
	LayoutInflater mInflater;
	GridView gridView;
	ViewHolder mHolder;
	// count表示图片总数，设置原则为如果只有一张图片，则图片宽度填满父布局，高度为手机宽一半高
	// 两张图片则宽度平分父布局宽度，高度为父布局三分之一，大于两张图片时每行最多显示三张图片，宽度平分
	int count, width;
	// 这里注意LayoutParams是属于AbsListView类的，因为本例中图片父布局是gridview
	LayoutParams params;
	BitmapUtils bitmapUtils;

	public PostInfo_TupianAdapter(Context context, List<String> list, GridView gridView,
			int width) {
		super();
		this.context = context;
		this.list = list;
		this.gridView = gridView;
		this.width = width;
		mInflater = LayoutInflater.from(context);
		bitmapUtils = new BitmapUtils(context);
		//加载中图片
		bitmapUtils.configDefaultLoadingImage(R.drawable.ic_launcher);
	}

	@Override
	public int getCount() {
		count = list.size();
		return count;
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return list.get(arg0);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	class ViewHolder {
		ImageView imageView;
	}

	@Override
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		if (arg1 == null) {
			arg1 = mInflater.inflate(R.layout.postinfo_tupian_gridview_item, null);
			mHolder = new ViewHolder();
			mHolder.imageView = (ImageView) arg1.findViewById(R.id.imageview);
			if (count == 1) {
				// 设置gridview每行只显示一张图片
				gridView.setNumColumns(1);
				// 只有一张图片时，图片宽与手机屏幕分辨率宽一致，高为宽分辨率的一半
				params = new LayoutParams(width, width / 2);
				mHolder.imageView.setLayoutParams(params);
			} else if (count == 2) {
				// 设置gridview每行只显示2张图片
				gridView.setNumColumns(2);
				// 只有两张图片时，图片宽度几乎为手机分辨率宽的一半，因为gridview设置了
				// 两张图片间距为1dp，所以这里减去了一个值3，可以自行调节此值大小
				params = new LayoutParams(width / 2 - 3, width / 3);
				mHolder.imageView.setLayoutParams(params);
			} else {
				// 设置gridview每行只显示3张图片
				gridView.setNumColumns(3);
				params = new LayoutParams(width / 3 - 3, width / 4);
				mHolder.imageView.setLayoutParams(params);
			}
			arg1.setTag(mHolder);
		} else {
			mHolder = (ViewHolder) arg1.getTag();
		}
		System.out.println("list.get(arg0)-----"+list.get(arg0));
		System.out.println("一共几张图片----"+getCount());
		//使用XUtils框架下载图片
		String url="http://" + MyApplication.getIP() + ":8080/Jinnang/img/"+list.get(arg0);
		bitmapUtils.display(mHolder.imageView, url);
		return arg1;
	}

}
